/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.saashousekeeper.creator;

import com.huawei.saashousekeeper.constants.DbPoolEnum;
import com.huawei.saashousekeeper.properties.DataSourceProperty;
import com.huawei.saashousekeeper.properties.DynamicSourceProperties;

import com.alibaba.druid.pool.DruidDataSource;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.SQLException;
import java.util.Optional;

import javax.sql.DataSource;

/**
 * druid数据源创建器
 *
 * @author lWX1156935
 * @since 2022/4/22
 */
@Slf4j
public class DruidDataSourceCreator implements DataSourceCreator {

    @Autowired
    protected DynamicSourceProperties config;

    @Override
    public DbPoolEnum getPoolType() {
        return DbPoolEnum.DB_DRUID;
    }

    @Override
    public DataSource createDataSource(DataSourceProperty dataSourceProperty) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(dataSourceProperty.getUsername());
        dataSource.setPassword(dataSourceProperty.getPassword());
        dataSource.setUrl(dataSourceProperty.getUrl());
        dataSource.setName(dataSourceProperty.getSourceName());
        String driverClassName = dataSourceProperty.getDriverClassName();
        if (StringUtils.isBlank(driverClassName)) {
            dataSource.setDriverClassName(driverClassName);
        }
        Optional.ofNullable(dataSourceProperty.getDruidConfig()).ifPresent(druidConfig -> {
            dataSource.configFromPropety(druidConfig.toProperties());

            // 连接参数单独设置
            dataSource.setConnectProperties(druidConfig.getConnectionProperties());
        });
        try {
            dataSource.init();
        } catch (SQLException e) {
            log.error("druid pool init failed {}", dataSourceProperty.getSourceName());
        }
        return dataSource;
    }
}
